// 引入axios
let axios = require("axios");
// 引入字体图标
require("../../libs/download/font_pnfugrcovra/iconfont.js");
require("../../libs/download/font_pnfugrcovra/iconfont.css");
require("../../libs/download/font_mf1p4fskz4/iconfont.css");

// 引入less
require("./zjf_sport_running.less");
document.addEventListener("DOMContentLoaded", function () {
	// axios工具
	axios.defaults.baseURL = "http://fitness.h5.itsource.cn:3701";
	let token = localStorage.getItem("token");
	axios.defaults.headers.common["Authorization"] = "Bearer " + token;
	// 封装获取函数
	function $(v) {
		return document.querySelector(v);
	}
	// 设置随机配速
	function num(max, min) {
		return Math.floor(Math.random() * (max - min + 1) + min);
	}
	// 封装时间转换函数
	function clock(n) {
		let hour = Math.floor(n / 3600);
		let minute = Math.floor((n % 3600) / 60);
		let second = Math.floor(n % 60);
		return `${
			hour > 9 ? hour : "0" + hour
		}:${minute > 9 ? minute : "0" + minute}:${second > 9 ? second : "0" + second}`;
	}
	let meter = 0; //运动距离
	let duration = 0; //运动时间
	let calorie = 0; //消耗卡路里
	let stop = null;
	// 动态渲染
	function star() {
		stop = setInterval(function () {
			// 计算距离
			meter += num(6, 4);
			$("#meter").textContent = (meter / 1000).toFixed(2);
			// 渲染速度
			$("#speed").textContent = `${num(6, 4)}米/秒`;
			// 动态累计时长
			duration++;
			$("#duration").textContent = clock(duration);
			// 计算卡路里
			calorie = Math.floor((meter * 60 * 1.036) / 1000);
			$("#calorie").textContent = `${calorie}千卡`;
		}, 1000);
	}
	star();
	// 点击暂停
	$("#n").addEventListener("click", function () {
		this.style.display = "none";
		$("#continue").style.display = "block";
		$("#continue").style.left = "30%";
		$("#over").style.display = "block";
		$("#over").style.right = "30%";
		clearInterval(stop);
	});
	// 点击继续
	$("#continue").addEventListener("click", function () {
		$("#n").style.display = "block";
		$("#over").style.display = "none";
		$("#continue").style.display = "none";
		star();
	});
	// 点击结束
	$("#over").addEventListener("click", function () {
		// 上传数据
		axios
			.post("/api/exercise/save", {
				type: 0,
				duration,
				meter,
				calorie,
			})
			.then((v) => {
				alert("运动结束");
				location.href = "./zjf_sport_run.html";
			});
	});
});
